package worldinruin.controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.AbstractAction;

import worldinruin.GameDataHandler;
import worldinruin.core.ISoldier;
import worldinruin.core.ITroop;
import worldinruin.core.imp.battle.Battle;
import worldinruin.resources.Components;

public class BattleController extends AbstractAction {
	
	private Battle battle;
	
	public void runBattle(Battle battle){
		
		
		List<ITroop> troops = battle.getTroops();
		
		while(!(battle.getAttacker().isDefeated() || battle.getDefender().isDefeated())){
			
			for (int i = 0; i < troops.size(); i++){
				int damage = calculateAttack(troops.get(i)) - calculateDefense(troops.get(1 - i));
				removeCasualties(troops.get(1 - i), damage);
			}
			
			
			
		}
		
	}
	
	public void removeCasualties(ITroop defender, int damage){
		
		int leftToRemove = damage;
		
		for (ISoldier soldier : GameDataHandler.getInstance().getSoldierTypes()){
			leftToRemove -= defender.remove(soldier, leftToRemove);
		}
		
	}
	
	public int calculateAttack(ITroop attacker){
		int total = 0;
		
		for (ISoldier soldier : attacker.getSoldiers()){
			total += attacker.getAmount(soldier) * soldier.getAttack();  
		}		
		
		return total;
	}
	
	public int calculateDefense(ITroop defender ){
		int total = 0;
		
		for (ISoldier soldier : defender.getSoldiers()){
			total += defender.getAmount(soldier) * soldier.getDefense();  
		}		
		
		return total;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		battle = GameDataHandler.getInstance().getBattle();
		Object obj = arg0.getSource();
		if(obj == Components.battleButton) {
			runBattle(battle);
		}
		else if(obj == Components.retreatButton) {
			
		}
	}



	

	

}
